package com.crm.controller;

import cn.hutool.core.bean.BeanUtil;

import com.crm.base.PageResult;
import com.crm.base.ResponseResult;
import com.crm.constant.SuperConstant;
import com.crm.domain.dto.CourseDto;
import com.crm.domain.dto.CourseQueryDTO;
import com.crm.domain.entity.Course;
import com.crm.service.ICourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@Api(tags = "课程管理")
@RequestMapping("/clues/course")
public class CourseController {
    @Resource
    private ICourseService courseService;

    @GetMapping("/list")
    @ApiOperation(value = "查询所有课程")
    public PageResult<List<Course>> courseByPage(CourseQueryDTO courseQueryDTO){

        return courseService.courseByPage(courseQueryDTO);
    }

    @PostMapping()
    @ApiOperation(value = "添加课程")
    public ResponseResult addCourse(@RequestBody CourseDto courseDto){
        Course course = BeanUtil.toBean(courseDto, Course.class);
        if(null == course.getCreateTime()){
            course.setCreateTime(LocalDateTime.now());
        }
        if(null == course.getUpdateTime()){
            course.setUpdateTime(LocalDateTime.now());
        }
        if(null == course.getCode()){
            String code = "";
            for (int i = 0; i < 5; i++) {
                code += SuperConstant.COURSE_CODE.charAt((int)(Math.random() * SuperConstant.COURSE_CODE.length()));
            }
            course.setCode(code);
        }
        courseService.save(course);
        return ResponseResult.success();
    }

    @DeleteMapping("/{ids}")
    @ApiOperation("批量删除课程")
    public ResponseResult deleteCourse(@PathVariable List<Long> ids){
        courseService.removeBatchByIds(ids);
        return ResponseResult.success();
    }

    @PutMapping()
    @ApiOperation("修改课程")
    public ResponseResult updateCourse(@RequestBody Course course){
        courseService.updateById(course);
        return ResponseResult.success();
    }
    @GetMapping("/{id}")
    @ApiOperation("查看课程")
    public ResponseResult<Course> getCourseById(@PathVariable Long id){
        Course course = courseService.getById(id);
        return ResponseResult.success(course);
    }

    @GetMapping("/listselect")
    @ApiOperation("查询所有课程")
    public ResponseResult<List<Course>> listSelectCourse(Long id){
        List<Course> list = null;
        if(null == id){
            list = courseService.list();
        }
        else{
            list.set( 0, courseService.getById(id));
        }
        return ResponseResult.success(list);
    }
}
